<?php
class Favorite extends MyBase{
	
	function __construct() {
		parent::__construct('favorite.id');
	}
	
	public function add_to_favorite($goodsid){
		$userinfo = & VS::get('userinfo');

		$id = empty($post['id']) ? 0 : intval($post['id']);
		$select = array('userid' => $userinfo['userid'], 'goodsid' => $goodsid);
		$rs = $this->db->get_row($this->tbname, $select, '`id`,`isdel`');
		if(!empty($rs)){
			if($rs['isdel'] == 0 && $id == 0){
				return 'exist';
			}else{
				$id = $rs['id'];
			}
		}
		$oGoods = new Goods();
		$goodsinfo = $oGoods->get_row($goodsid, '`name`,`price`');
		$data = array(
			'userid'		=> $userinfo['userid'],
			'goodsid'		=> $goodsid,
			'goodsname'		=> $goodsinfo['name'],
			'price'			=> $goodsinfo['price'],
			'isdel'			=> 0,
		);
		if($id > 0){
			$data['updatetime'] = TIME; 
			$r = $this->db->update($this->tbname, array('id' => $id), $data);
		}else{
			$data['addtime'] = TIME;
			$r = $id = $this->db->insert($this->tbname, $data);
			if($r > 0){
				$oGoods->inc_trends($goodsid, 'favorites');

				// 增加一条消息
				$oNotice = new Notice();
				$oNotice->add(Notice::FAVORITE, $goodsid);
			}
		}
		if ($r > 0) {
			return 'succ';
		}else{
			return 'fail';
		}
	}
					
	public function del($post){
		if(!is_array($post['list']))$post['list'] = array($post['list']);
		$iRtn = 0;
		foreach($post['list'] as $id){
			$r = $this->db->update($this->tbname, array('id' => $id), array('isdel' => 1));
			if($r > 0){
				$iRtn ++;
			}
		}
		return $iRtn;
	}
	
	public function get_row($id, $fields = '*', $cache = false){
		return $this->db->get_row($this->tbname, array('id' => $id), $fields);
	}

	public function get_list($fields = '*', $select = array(), $order = array(), $page = 1, $size = 10, $offset = PAGE_OFFSET){
		$select['kept'] = '';
		if(!empty($select['goodsname'])){
			$select['kept'] .= " AND `goodsname` LIKE '%{$select['goodsname']}%'";
			unset($select['goodsname']);
		}
		if(!empty($select['price_min'])){
			$select['kept'] .= " AND `price`>{$select['price_min']}";
		}
		if(!empty($select['price_maxs'])){
			$select['kept'] .= " AND `price`>{$select['price_maxs']}";
		}
		$select['isdel'] = 0;
		$list = $this->db->get_list($this->tbname, $fields, $select, $order, $page, $size, $offset);
		if(!empty($list['list'])){
			$oGoods = new Goods();
			foreach ($list['list'] as $key => $row) {
				$row['goodsinfo'] = $oGoods->get_row($row['goodsid']);
				$row['trends'] = $oGoods->get_trends($row['goodsid']);
				$list['list'][$key] = $row;
			}
		}
		return $list;
	}
}
?>